import tabbar from '../../utils/tabbar'
const app = getApp()
let user
const api = wx.getStorageSync('api')
Page({
  data: {
    active: 0, // 底部tabbar
    current: 1, // 分页加载
    num: 10, // 一页几个
    addCarShow: false, // 加入购物车显示与隐藏
    specification: [], // 商品规格信息
    currentIndex: 0, // 当前选中加入购物车商品的序号
    sIndex: 0, // 当前选中规格
    buyNum: 1 // 商品数量
  },

  onTabbarChange(e) {
    tabbar.redirectTo(e.detail)
  },

  // 获取首页信息
  getGoods() {
    const url = api.index + `?page=${this.data.current}&limit=${this.data.num}`
    app.$http.get(url)
      .then(res => {
        console.log('获取首页信息', res)
        this.setData({
          ...res.data
        })
      })
  },

  onLoad: function (options) {
    this.getGoods()
  },

  // 商品规格点击
  sIndexClick(e) {
    this.setData({
      sIndex: e.currentTarget.dataset.index
    })
  },

  // 关闭加入购物车
  closeAddCarCard() {
    this.setData({
      addCarShow: false
    });
  },

  // 显示加入购物车
  showAddCar(e) {
    user = wx.getStorageSync('user')
    if (typeof user != 'object') {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }
    let com = this.selectComponent('#addcar')
    let index = e.currentTarget.dataset.index
    let good = this.data.goods[index]
    com.show(good)
  },

  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
    wx.showLoading({
      title: '加载中',
    })
    if (this.data.goodsTotal / 10 < this.data.current) {
      this.setData({
        current: 1
      })
    }
    const url = api.index + `?page=${this.data.current + 1}&limit=${this.data.num}`
    app.$http.get(url)
      .then(res => {
        this.setData({
          current: this.data.current + 1,
          goods: this.data.goods.concat(res.data.goods)
        })
        wx.hideLoading()
      })
  },

  // 购买数量改变
  onChange(e) {
    this.setData({
      buyNum: e.detail
    })
  },

  //回到顶部
  goTop: function (e) {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },

  // 前往搜索页
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  // 跳转商品详情页
  toGoodPage(e) {
    let id = e.currentTarget.dataset.id
    console.log(id)
    wx.navigateTo({
      url: `/pages/goodPage/goodPage?id=${id}`
    })
  },

  buyGood() {
    wx.showToast({
      title: '请前往购物车结算',
      icon: 'none',
      duration: 2000
    })
  }
})